# 定义变量
APP_DIR="/home/admin/app"
LOGCENTER_DIR="$APP_DIR/sclogcenter_rbac_read"
IMAGE_NAME="sclogcenter_rbac_read"
CONTAINER_NAME="sclogcenter_rbac_read"
CONTAINER_PORT="7012"

# 进入应用目录
cd "$APP_DIR" || { echo "无法进入目录 $APP_DIR"; exit 1; }

# 清理并创建 logcenter 目录
rm -rf "$LOGCENTER_DIR" && mkdir -p "$LOGCENTER_DIR"

# 解压包
if [[ -f "read_package.tgz" ]]; then
    tar -xzf "read_package.tgz" -C "$LOGCENTER_DIR" || { echo "解压失败"; exit 1; }
else
    echo "文件 read_package.tgz 不存在"
    exit 1
fi

# 进入 logcenter 目录
cd "$LOGCENTER_DIR" || { echo "无法进入目录 $LOGCENTER_DIR"; exit 1; }

# 改进的容器删除逻辑 - 忽略错误继续执行
echo "检查并删除容器 $CONTAINER_NAME..."
if docker ps -q -f name="$CONTAINER_NAME" | grep -q .; then
    echo "停止正在运行的容器 $CONTAINER_NAME..."
    docker stop "$CONTAINER_NAME" 2>/dev/null || echo "容器未运行或停止失败，继续..."
fi

if docker ps -aq -f name="$CONTAINER_NAME" | grep -q .; then
    echo "删除容器 $CONTAINER_NAME..."
    docker rm "$CONTAINER_NAME" 2>/dev/null || echo "删除容器失败，继续..."
fi

# 检查并删除镜像
if docker image inspect "$IMAGE_NAME" > /dev/null 2>&1; then
    echo "删除镜像 $IMAGE_NAME..."
    docker rmi -f "$IMAGE_NAME" || { echo "删除镜像失败"; exit 1; }
fi

# 构建镜像
echo "构建镜像 $IMAGE_NAME..."
docker build -t "$IMAGE_NAME" . || { echo "镜像构建失败"; exit 1; }

# 运行容器
echo "运行容器 $CONTAINER_NAME..."
docker run -d -p $CONTAINER_PORT:80 --name "$CONTAINER_NAME" "$IMAGE_NAME" || { echo "启动容器失败"; exit 1; }

echo "容器 $CONTAINER_NAME 启动成功，映射到主机的 $CONTAINER_PORT 端口。"